package com.rzx.mybackend.config.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rzx.mybackend.entity.Game;
import com.rzx.mybackend.vo.GameCommentVO;
import jakarta.websocket.EncodeException;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * WebSocketEndpoint
 *
 * @author renzhexian
 * @date 2025/7/23
 */
@Component
@ServerEndpoint("/push")  // WebSocket 连接路径
public class WebSocketEndpoint {
    // 存储所有会话
    private static final CopyOnWriteArraySet<Session> sessions = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        try {
            // TODO: 出于安全性考虑，此处应做token验证，验证通过后再发送连接成功消息，否则关闭连接（此处暂时放行）
            session.getBasicRemote().sendText("SERVER: 连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
    }

    // 静态方法供外部调用推送
    public static void pushToAll(GameCommentVO gameCommentVO) {
        for (Session session : sessions) {
            if (session.isOpen()) {
                try {
                    session.getBasicRemote().sendText(new ObjectMapper().writeValueAsString(gameCommentVO));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
